<!--
    -  Copyright (c) 2018-2025, haohanwork.com All rights reserved.
  -->
<template>
    <div class="execution">
        <basic-container>
            <avue-crud ref="crud"
                       :page.sync="page"
                       :data="tableData"
                       :permission="permissionList"
                       :table-loading="tableLoading"
                       :option="tableOption"
                       @on-load="getList"
                       @search-change="searchChange"
                       @refresh-change="refreshChange"
                       @row-update="handleUpdate"
                       @row-save="handleSave"
                       @row-del="rowDel">
                   <template slot="menuLeft">
                     <div class="tabs">
                       <div :class="{active:1==current}" @click="toggleList(1)">审核</div>
                       <div :class="{active:2==current}" @click="toggleList(2)">分配</div>
                       <div :class="{active:3==current}" @click="toggleList(3)">采购</div>
                     </div>
                  </template>
                <template slot-scope="scope" slot="menu">
                    <el-button type="text" size="small" plain v-if="scope.row.taskActionType=='2' && scope.row.taskStatus=='1'" @click="allocation(scope.row)">分配采购员</el-button>
                    <el-button type="text" size="small" plain v-if="scope.row.taskStatus != '3' && scope.row.purchaseStatus=='3'" @click="purchaseBtn(scope.row)">采购</el-button>
                    <el-button type="text" size="small" plain v-if="scope.row.purchaseStatus=='5' && scope.row.taskStatus=='2'" @click="enterWarehouse(scope.row)">入库</el-button>
                    <el-button type="text" size="small" plain v-if="scope.row.taskStatus=='2' && scope.row.purchaseStatus=='4'" @click="confirmGoods(scope.row)">揽货确认</el-button>
                </template>
                <template slot="menuLeft">
                    <div style="width: 300px">
                        <el-dialog title="分配采购员" :visible.sync="dialogTableVisible">
                            <el-table ref="multipleTable" :data="gridData" border tooltip-effect="dark" style="width: 100%"
                                      @selection-change="handleSelectionChange">
                                <el-table-column type="selection" width="55"></el-table-column>
                                <el-table-column prop="id" label="员工编号" show-overflow-tooltip></el-table-column>
                                <el-table-column prop="name" label="姓名"></el-table-column>
                                <el-table-column fixed="right" label="操作">
                                    <template slot-scope="scope">
                                        <el-button type="text" size="small" @click="toggleSelection(scope.row)">选定</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-dialog>
                    </div>
                </template>
            </avue-crud>
        </basic-container>
        <template>
            <el-dialog title="入库管理" :visible.sync="dialogForm">
                <el-form :model="enterData">
                    <el-form-item label="商品名称" :label-width="formLabelWidth">
                        <el-tag> {{enterData.goodsName}}</el-tag>
                    </el-form-item>
                    <el-form-item label="实际入库数量" :label-width="formLabelWidth">
                        <el-input v-model="enterData.realBuyNum" v-enter-number type="number" style="width: 188px" oninput="if(value.length>8)value=value.slice(0,8)" autocomplete="off"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialogForm = false">取 消</el-button>
                    <el-button type="primary" @click="confirm">确 定</el-button>
                </div>
            </el-dialog>
        </template>
        <template>
          <el-dialog title="揽货确认" :visible.sync="isconfirmGoods">
            <el-form :model="firmGoods">
              <el-form-item label="商品名称" :label-width="formLabelWidth">
                <el-tag> {{firmGoods.goodsName}}</el-tag>
              </el-form-item>
              <el-form-item label="实际揽货数量" :label-width="formLabelWidth">
                <el-input v-model="firmGoods.realBuyNum" autocomplete="off" v-enter-number type="number" style="width: 188px" oninput="if(value.length>8)value=value.slice(0,8)"></el-input>
              </el-form-item>
              <el-form-item label="付款方式" :label-width="formLabelWidth">
                  <el-radio-group v-model="firmGoods.payType">
                      <el-radio
                              v-for="item in payTypeOpt"
                              :key="item.value"
                              :label="item.value">{{item.label}}
                      </el-radio>
                  </el-radio-group>
              </el-form-item>
              <el-form-item label="揽货方式" :label-width="formLabelWidth">
                <el-select v-model="firmGoods.receiveType" placeholder="揽货方式">
                  <el-option label="自提" value="1"></el-option>
                  <el-option label="送货上门" value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="执行备注" :label-width="formLabelWidth">
                <el-input v-model="firmGoods.actionDesc" type="textarea" autocomplete="off"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="isconfirmGoods = false">取 消</el-button>
              <el-button type="primary" @click="sure">确 定</el-button>
            </div>
          </el-dialog>
        </template>
        <template>
            <el-dialog title="采购" :visible.sync="confirmSupplier">
                <el-form :model="purchaseData">
                    <el-form-item label="商品名称" :label-width="formLabelWidth" >
                        <el-tag>{{purchaseData.goodsName}}</el-tag>
                    </el-form-item>
                    <el-form-item label="下单数量" :label-width="formLabelWidth" >
                        <el-tag>{{purchaseData.needBuyNum}}</el-tag>
                    </el-form-item>
                    <el-form-item label="市场价格" :label-width="formLabelWidth" >
                        <el-tag>{{purchaseData.marketPrice}}&nbsp;元/{{purchaseData.unit}}</el-tag>
                    </el-form-item>
                    <el-form-item label="采购价格" :label-width="formLabelWidth">
                        <el-input v-model="purchaseData.realBuyPrice" type="number" oninput="if(value.length>8)value=value.slice(0,8)" style="width: 188px"></el-input>&nbsp;元/{{purchaseData.unit}}
                    </el-form-item>
                    <el-form-item label="选择供应商" :label-width="formLabelWidth">
                        <el-select v-model="purchaseData.supplierName" placeholder="选择供应商" @change="getSup">
                            <el-option v-for="item in supList" :label="item.supplierName" :value="item.id" :key="index"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="支付类型" :label-width="formLabelWidth">
                        <el-radio-group v-model="purchaseData.payType">
                            <el-radio
                                    v-for="item in payTypeOpt"
                                    :key="item.value"
                                    :label="item.value">{{item.label}}
                            </el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="confirmSupplier = false">取 消</el-button>
                    <el-button type="primary" @click="purchase">确 定</el-button>
                </div>
            </el-dialog>
        </template>
    </div>
</template>
<!-- 采购退货 -->
<script>
    import {
        fetchList,
        queryEmployeeList,
        appointTask,
        singlePurchase,
        purchaseProductEntry,
        confirmGood
    } from '@/api/scm/purchase/purchase_task'
    import {
      fetchList as fetchcList,
    } from '@/api/supply/supplier'
    import {
        tableOption
    } from '@/const/crud/scm/purchase/purchase_task'
    import {
        mapGetters
    } from 'vuex'
    import Util from '@/util/pds/utils'
    let cookieUtil = new Util();
    import {getStore, setStore} from "@/util/store";
    export default {
        name: 'purchaseTask',
        data() {
            return {
                tableData: [],
                gridData:[],
                enterData:{},
                purchaseData:{
                  payType: '1'
                },
                selectIndex: '',
                index:'',
                dialogTableVisible: false,
                dialogFormVisible:false,
                confirmSupplier:false,
                dialogForm:false,
                isconfirmGoods:false,
                formLabelWidth: '120px',
                multipleSelection: [],
                page: {
                    total: 0, // 总页数
                    currentPage: 1, // 当前页数
                    pageSize: 20 // 每页显示多少条
                },
                tableLoading: false,
                tableOption: tableOption,
                supList:[],
                payTypeOpt: this.$dic.pdsPayType,
                firmGoods:{
                  pmId:'',
                  taskId:'',
                  realBuyNum:0,
                  payType:'1',
                  receiveType:'2',
                  actionDesc:'',
                  goodsName:'',
                },
                current:1,
                column: [
                  {
                    label: '采购单号',
                    prop: 'purchaseSn',
                    search: true,
                    sortable: true,
                  },
                  {
                    label: '商品名称',
                    prop: 'goodsName',
                  },
                  {
                    label: '商品规格',
                    prop: 'modelName',
                  }, {
                    label: '单位',
                    prop: 'unit'
                  },
                  {
                    label: '商品图片',
                    prop: 'goodsImg',
                    type: 'upload',
                    imgWidth: 100,
                    imgHeight: 50,
                    listType: 'picture-img'
                  }, {
                    label: '市场价',
                    prop: 'marketPrice'
                  }, {
                    label: '采购价格',
                    prop: 'buyPrice'
                  }, {
                    label: '采购数量',
                    prop: 'needBuyNum'
                  }, {
                    label: '实际采购数量',
                    prop: 'realBuyNum'
                  },{
                    label: '执行人',
                    prop: 'transactorName'
                  },{
                    label: '任务执行方式',
                    prop: 'taskActionType',
                    dicUrl: '/admin/dict/type/scm_task_action_type',
                  },{
                    label: '任务状态',
                    prop: 'taskStatus',
                    type: 'select',
                    dicUrl: '/admin/dict/type/scm_task_status',
                    search: true,

                  },{
                    label: '采购状态',
                    prop: 'purchaseStatus',
                    type: 'select',
                    dicUrl: '/admin/dict/type/scm_purchase_status',
                    search: true,

                  },{
                    label: '采购截止时间',
                    prop: 'deadlineTime',
                  },{
                    label: '配送日期',
                    prop: 'actionTime',
                    type: 'datetime',
                    format: "yyyy-MM-dd",
                    valueFormat: "yyyy-MM-dd HH:mm:ss",
                    search: true,
                    hide: true
                  }
                ],
                splumn:[
                  {
                    label: '采购单号',
                    prop: 'purchaseSn',
                    search: true,
                    sortable: true,
                  },{
                    label: '执行人',
                    prop: 'transactorName'
                  },{
                    label: '任务执行方式',
                    prop: 'taskActionType',
                    dicUrl: '/admin/dict/type/scm_task_action_type',
                  },{
                    label: '任务状态',
                    prop: 'taskStatus',
                    type: 'select',
                    dicUrl: '/admin/dict/type/scm_task_status',
                    search: true,

                  },{
                    label: '采购状态',
                    prop: 'purchaseStatus',
                    type: 'select',
                    dicUrl: '/admin/dict/type/scm_purchase_status',
                    search: true,

                  },{
                    label: '采购截止时间',
                    prop: 'deadlineTime',
                  },{
                    label: '配送日期',
                    prop: 'actionTime',
                    type: 'datetime',
                    format: "yyyy-MM-dd",
                    valueFormat: "yyyy-MM-dd HH:mm:ss",
                    search: true,
                    hide: true
                  }
                ]
            }
        },
        computed: {
            ...mapGetters(['permissions']),
            permissionList() {
                return {
                    addBtn: this.vaildData(this.permissions.purchase_purchasetask_add, true),
                    delBtn: this.vaildData(this.permissions.purchase_purchasetask_del, true),
                    editBtn: this.vaildData(this.permissions.purchase_purchasetask_edit, true)
                };
            }
        },
        created() {
            this.init();
        },
        methods: {
            init() {
                //查询采购员
                queryEmployeeList({
                    pmId:getStore({name: "pmId"}),
                    purchaseEmployeeType: "3"
                }).then(res => {
                    this.gridData = res.data.data
                })
                this.getsupList();
            },
            //展示采购任务列表
            getList(page, params={}) {
                this.tableLoading = true
                params.pmId = getStore({name: "pmId"});
                params.taskActionType = this.current;
                if(params.taskActionType == 1){
                  this.tableOption.column = this.splumn;
                }else{
                  console.log(tableOption);
                  this.tableOption.column = this.column;
                }
                fetchList(Object.assign({
                    current: page.currentPage,
                    size: page.pageSize
                }, params)).then(res => {
                    this.tableData = res.data.data.records;
                    this.page.total = res.data.data.total
                    this.tableLoading = false
                })
            },
            //获取供应商
            getsupList(params) {
              fetchcList(Object.assign({
                current: 1,
                size: 20
              }, params)).then(response => {
                this.supList = response.data.data.records
              })
            },
            //分配
            allocation(row) {
                // console.log("tableData",this.tableData)
                this.dialogTableVisible = true;
                this.selectIndex = row.$index;
            },

            //设置采购员
            toggleSelection(row) {
                this.tableData[this.selectIndex].transactorName = row.name;
                this.tableData[this.selectIndex].transactorId = row.id;
                let param = {};
                param.pmId= getStore({name: "pmId"});
                param.employeeId=row.id;
                param.id=this.tableData[this.selectIndex].id
                // console.log("param", param)
                appointTask(param).then(res =>{
                    if(res.data.code==0){
                        this.$message.success("设置采购员成功");
                        let query = {
                          taskActionType:this.current
                        };
                        this.getList(this.page, query);
                    }else{
                        this.$message.error("设置采购员失败")
                    }
                });
                this.dialogTableVisible = false
            },
            //采购按钮
            purchaseBtn(row){
                this.confirmSupplier = true;
                this.purchaseData = row;
                this.purchaseData.payType = '1';
            },
            getSup(val){
              this.purchaseData.supplierId = val;
              this.supList.forEach(item=>{
                if(item.id == val){
                  this.purchaseData.supplierName = item.supplierName;
                }
              })
            },
            //采购员确认供应商
            purchase(){
                let param = {};
                param.pmId=getStore({name: "pmId"});
                param.purchaseDetailSn = this.purchaseData.purchaseDetailSn;
                param.realBuyPrice = this.purchaseData.realBuyPrice;
                param.supplierName = this.purchaseData.supplierName;
                param.supplierId = this.purchaseData.supplierId;
                param.payType = this.purchaseData.payType;
                param.taskId=this.purchaseData.id;
                if(!param.supplierId){
                  this.$message.error("请选择供应商");
                  return false
                }
                if(!param.realBuyPrice){
                  this.$message.error("请输入价格");
                  return false
                }
                singlePurchase(param).then(res=>{
                    if(res.data.code==0){
                        this.$message.success("确认供应商成功");
                        let query = {
                          taskActionType:this.current
                        };
                        this.getList(this.page, query);
                    }else{
                        this.$message.error("确认供应商失败")
                    }
                })
                this.confirmSupplier = false;
            },

            //采购明细货品 实际入库
            enterWarehouse(row){
                this.dialogForm = true;
                // console.log("row",row)
                this.enterData = row;
            },
            //确定入库
            confirm(){
                let param = {};
                param.pmId=getStore({name: "pmId"});
                param.purchaseDetailSn = this.enterData.purchaseDetailSn;
                param.taskId=this.enterData.id;
                param.realBuyNum=this.enterData.realBuyNum;
                purchaseProductEntry(param).then(res =>{
                    if(res.data.data==true){
                        this.$message.success("入库成功");
                        let query = {
                          taskActionType:this.current
                        };
                        this.getList(this.page, query);
                    }else{
                        this.$message.error("入库失败")
                    }
                });
                this.dialogForm = false;
            },
            //揽货确认
            confirmGoods(row){
              this.firmGoods.pmId = row.pmId;
              this.firmGoods.taskId = row.id;
              this.firmGoods.realBuyNum = row.needBuyNum;
              this.firmGoods.goodsName = row.goodsName;
              this.isconfirmGoods = true;
            },
            sure(){
              let param = this.firmGoods;
              confirmGood(param).then(res =>{
                if(res.data.code==0){
                  this.$message.success("揽货成功");
                  let query = {
                    taskActionType:this.current
                  };
                  this.getList(this.page, query);
                }else{
                  this.$message.error("揽货失败")
                }
              });
              this.isconfirmGoods = false;
            },
            rowDel: function (row, index) {
                var _this = this
                this.$confirm('是否确认删除ID为' + row.id, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(function () {
                    return delObj(row.id)
                }).then(data => {
                    _this.tableData.splice(index, 1)
                    _this.$message({
                        showClose: true,
                        message: '删除成功',
                        type: 'success'
                    })
                    this.getList(this.page)
                }).catch(function (err) {
                })
            },
            /**
             * @title 数据更新
             * @param row 为当前的数据
             * @param index 为当前更新数据的行数
             * @param done 为表单关闭函数
             *
             **/
            handleUpdate: function (row, index, done) {
                putObj(row).then(data => {
                    this.tableData.splice(index, 1, Object.assign({}, row))
                    this.$message({
                        showClose: true,
                        message: '修改成功',
                        type: 'success'
                    })
                    done()
                    this.getList(this.page)
                })
            },
            /**
             * @title 数据添加
             * @param row 为当前的数据
             * @param done 为表单关闭函数
             *
             **/
            handleSave: function (row, done) {
                addObj(row).then(data => {
                    this.tableData.push(Object.assign({}, row))
                    this.$message({
                        showClose: true,
                        message: '添加成功',
                        type: 'success'
                    })
                    done()
                    this.getList(this.page)
                })
            },

            handleSelectionChange(val) {
                this.multipleSelection = val;
            },

            /**
             * 搜索回调
             */
            searchChange(form, done) {
                this.getList(this.page, form);
                done();
            },
            /**
             * 刷新回调
             */
            refreshChange(info) {
    this.getList(this.page, this.filterForm(info.searchForm));
},
            toggleList(type){
                this.current = type;
                let query = {
                  taskActionType:type
                };
              this.getList(this.page, query);
            },
            /**
             * 页面跳转
             */
            jumpToAdd() {
                this.$router.push({path: '/order_manage/valetOrder'})
            },
            jumpToDetail() {
                this.$router.push({path: '/order_manage/detail'})
            }
        }
    }
</script>

<style lang="scss" scoped>
  .active{
    background-color: #fff;
    color: #1E90FF;
  }
  .tabs{
    overflow: hidden;
  }
  .tabs div{
    width: 100px;
    text-align: center;
    float: left;
    border-bottom: 2px solid #eee;
    cursor: pointer;
    padding-bottom: 10px;
  }
  .tabs .active{
    border-color: #1E90FF;
  }
</style>
